'use strict';

const Service = require('egg').Service;

class AddressService extends Service {
  async insert(params) {
    const item = await this.get(params.product_id, params.user_id);
    console.log(item);
    if (item) {
      const res = await this.app.mysql.update('car', {
        id: item.id,
        num: item.num + 1,
      });
      return res;
    }
    const res = await this.app.mysql.insert('car', {
      ...params,
      num: 1,
    });
    return res;
  }

  async update(params) {
    console.log(params);
    const res = await this.app.mysql.update('car', {
      ...params,
    });
    return res;
  }

  async select(user_id) {
    const sql = `
      select 
        c.id,
        c.product_id,
        c.num,
        c.is_active,
        p.title,
        p.cover,
        p.price,
        p.oldPrice,
        p.count,
        p.volume 
      from car c left join product p on c.product_id = p.id 
      where c.user_id='${user_id}'
    `;
    const res = await this.app.mysql.query(sql);
    return res;
  }

  async get(product_id, user_id) {
    const res = await this.app.mysql.get('car', {
      product_id,
      user_id,
    });
    return res;
  }

  async delete(id) {
    const res = await this.app.mysql.delete('car', { id });
    return res;
  }
}

module.exports = AddressService;
